package pers.ht.mbpo.dao;

import pers.ht.mbpo.bean.Notice;
import pers.ht.mbpo.util.DBUtil;
import pers.ht.mbpo.util.DaoUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class NoticeDao {
    //添加
    public void insert(Notice n) {
        String sql = "INSERT INTO notice(noticeTitle,noticeDesc) VALUES (?,?)";
        DaoUtil.update(sql, n.getNoticeTitle(), n.getNoticeDesc());
    }

    //删除
    public void delete(String id) {
        String sql = "DELETE FROM notice WHERE noticeId = ?";
        DaoUtil.update(sql, id);
    }

    //修改
    public void edit(Notice n) {
        String sql = "UPDATE notice SET noticeTitle = ?,noticeDesc = ? WHERE noticeId = ?";
        DaoUtil.update(sql, n.getNoticeTitle(), n.getNoticeDesc(), n.getNoticeId());
    }

    //校验主键唯一
    public boolean checkId(String id) {
        return DaoUtil.checkId("notice", "noticeId", id);
    }

    //查询所有
    public List<Notice> query() {
        List<Notice> notices = new ArrayList<Notice>();
        String sql = "SELECT * from notice WHERE 1=1";
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while (rs.next()) {
                Notice a = new Notice();
                a.setNoticeId(rs.getInt("noticeId"));
                a.setNoticeTitle(rs.getString("noticeTitle"));
                a.setNoticeDesc(rs.getString("noticeDesc"));
                notices.add(a);
            }
            DBUtil.close(rs, stat, conn);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        return notices;
    }

    //按主键查询一个
    public Notice queryOne(String noticeId) {
        Notice a = new Notice();
        String sql = "SELECT * from notice WHERE noticeId = '" + noticeId + "'";
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while (rs.next()) {
                a.setNoticeId(rs.getInt("noticeId"));
                a.setNoticeTitle(rs.getString("noticeTitle"));
                a.setNoticeDesc(rs.getString("noticeDesc"));
            }
            DBUtil.close(rs, stat, conn);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        return a;
    }
}
